// 采用node js的方式build

'use strict';
import webpack from 'webpack';
import configFactory from '../config/webpack.config';
const chalk = require('chalk');

// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', (err) => {
    throw err;
});

const config = configFactory(
    {
        production: true,
    },
    {},
);

function build() {
    console.log('Creating an optimized production build...');
    const compiler = webpack(config);
    return new Promise((resolve, reject) => {
        compiler.run((err, stats) => {
            if (err) {
                if (!err.message) {
                    return reject(err);
                }
                console.log(err);
            }
            const resolveArgs = {
                stats,
            };
            return resolve(resolveArgs);
        });
    });
}

build()
    .then(
        () => {
            console.log(chalk.green('Compiled successfully.\n'));
            console.log('你可以通过以下方式本地预览.\n');
            console.log('$ npm install -g serve\n');
            console.log('$ serve -s dist \n');
        },
        (err) => {
            if (err && err.message) {
                console.log(err.message);
            }
            console.log(chalk.red('Failed to compile.\n'));
            process.exit(1);
        },
    )
    .catch((err) => {
        if (err && err.message) {
            console.log(err.message);
        }
        console.log(chalk.red('Failed to compile.\n'));
        process.exit(1);
    });
